﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing.Drawing2D;
using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.ComponentModel;
using System.Windows;
using System.Drawing.Imaging;
using System.Drawing;

namespace iMagistic
{
    class imageItem : INotifyPropertyChanged
    {
        public string imagePath { get; private set; }
        public string thumbPath { get; private set; }

        public System.Windows.Size thumbSize  { get; private set; }
        public string imageName { get; private set; }

        public System.Windows.Size originaImSize { get; set; }

        public int rotationAngle { get;  set; }

        public double aspectRatio { get; set; }

        public bool isCropped { get; set; }

        public double[] cropMargins { get;  set; }

        private BitmapSource _thumbnail = null;

        /// <summary>
        /// INotofyPropertyChanged event
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        ///Creates an instance of the imageItem
        /// </summary>
        /// <param name="path">URL of the image to handle</param>
        /// <param name="thumbMaxHeight">maximal height of the thumbnail</param>
        public imageItem(string path, int thumbMaxHeight)
        {
            this.thumbSize = new System.Windows.Size(0, thumbMaxHeight);   // width = auto, height = thumbMaxHeight
            this.imagePath = path;
            this.imageName = Path.GetFileName(path);
            cropMargins = new double[] { 0,0,0,0};
            isCropped = false;
            aspectRatio = 1;
        }

        /// <summary>
        /// Gets the thumbnail of the image source
        /// </summary>
        public BitmapSource GetThumbnail()
        {
                if ((_thumbnail == null))
                {
                    ThumbGenerator tg = new ThumbGenerator();
                    _thumbnail = tg.GetThumbnail(imagePath, (int)thumbSize.Height, false);
                    this.originaImSize = tg.imageSize;
                }
                return _thumbnail;
        }

        /// <summary>
        /// Releases the resources used
        /// </summary>
        public void Dispose()
        {
            _thumbnail = null;
        }

        #region Handlers
        public void OnPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        #endregion


        public static Bitmap cropImage(Bitmap img, Rectangle cropArea)
        {
            Bitmap bmpImage = new Bitmap(img);
            Bitmap bmpCrop = bmpImage.Clone(cropArea,
            bmpImage.PixelFormat);
            return (bmpCrop);
        }





        public void saveImage(string outputPath)
        {
            BitmapImage bImage = new BitmapImage();
            bImage.BeginInit();
            bImage.UriSource = new Uri(imagePath);
            bImage.CacheOption = BitmapCacheOption.None;
            bImage.CreateOptions = BitmapCreateOptions.DelayCreation; //important for performance
            bImage.EndInit();

            if (bImage.CanFreeze) //to avoid memory leak
                bImage.Freeze();

            CroppedBitmap cbm = new CroppedBitmap();

            cbm.BeginInit();
            cbm.Source = bImage;
            cbm.SourceRect = new Int32Rect((int)cropMargins[0], (int)cropMargins[1], (int)cropMargins[2], (int)cropMargins[3]);
            cbm.EndInit();


            DirectoryInfo dir = new DirectoryInfo(outputPath);
            if (!dir.Exists)
            {
                dir.Create();
            }


            FileStream filestream = new FileStream(outputPath + Path.DirectorySeparatorChar + imageName, FileMode.Create);
            JpegBitmapEncoder encoder = new JpegBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(cbm));
            encoder.Save(filestream);
        }



        public void save(string path, long quality)
        {

            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.UriSource = new Uri(imagePath);
            image.CacheOption = BitmapCacheOption.None;
            image.CreateOptions = BitmapCreateOptions.DelayCreation; //important for performance
            image.EndInit();

            if (image.CanFreeze) //to avoid memory leak
                image.Freeze();



            // Encoder parameter for image quality
            EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);

            // Jpeg image codec
            ImageCodecInfo jpegCodec = this.getEncoderInfo("image/jpeg");

            if (jpegCodec == null)
                return;

            EncoderParameters encoderParams = new EncoderParameters(1);
            encoderParams.Param[0] = qualityParam;

            //img.Save(path, jpegCodec, encoderParams);
        }
        private ImageCodecInfo getEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }
    }
}
